package kr.co.mcshop;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import kr.co.mcshop.product.ProductService;
import kr.co.mcshop.qna.QnA;
import kr.co.mcshop.qna.QnAService;
import kr.co.mcshop.review.ReviewBoard;
import kr.co.mcshop.review.ReviewBoardService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

/**
 * Handles requests for the application home page.
 */
@Controller
public class HomeController {
	@Autowired
	ProductService ps;
	@Autowired
	   private QnAService qnaService;
	@Autowired
    private ReviewBoardService board;
	
	@RequestMapping(value="/")
	public String Main(Model model, @RequestParam Map map){
		List<Map> list = ps.getAllProduct(map);
		HashMap imgArray = new HashMap();
		if(list.size() != 0){
			for(int i=0; i<list.size(); i++){
				Map mapforImage = (Map) list.get(i);
				String[] image = mapforImage.get("IMAGE").toString().split("[/]");
				list.get(i).put("mainImage", image[0]);
			}
			model.addAttribute("ItemList", list);
		}
		List<QnA> list1 = qnaService.selectqna(map);
	     model.addAttribute("qnaList", list1);
		
	    List<ReviewBoard> BOARD = board.getAllBoard(map);
	     model.addAttribute("BOARD", BOARD);
	      

		      
		return "main";
	}
	
	@RequestMapping(value="/admin")
	public String adminForm(){
		return "admin/product/ProductListForm";
	}
	
	@RequestMapping(value = "/ajax", method = RequestMethod.POST, produces="text/plain;charset=UTF-8")
	@ResponseBody
	public String ajax(Locale locale, Model model, @RequestParam Map map,
			HttpServletResponse response) {
		
		System.out.println(map);
		try {
			Thread.sleep(3000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Gson gson = new Gson();
		return gson.toJson(map);
	}
}
